﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using Twi.COMMON.HTTP;

namespace Twi.COMMON.WPF
{
    /// <summary>
    /// ucPage.xaml 的交互逻辑
    /// </summary>
    public partial class PageComponent : UserControl
    {
        public PageComponent()
        {
            InitializeComponent();
            PageIndex = 0;           
        }

        public string ServerPageUri { get; set; }

        private QueryConditionComponent _queryConditionComponent;
        public QueryConditionComponent QueryConditionComponent 
        {
            get { return _queryConditionComponent; }
            set 
            {                
                _queryConditionComponent = value;
                _queryConditionComponent.TxtTextContent.KeyDown += new KeyEventHandler(TxtTextContent_KeyDown);
            }
        }

        private QueryConditionComponent2 _queryConditionComponent2;
        public QueryConditionComponent2 QueryConditionComponent2 
        {
            get { return _queryConditionComponent2; }
            set
            {
                _queryConditionComponent2 = value;
                _queryConditionComponent2.TxtTextContent.KeyDown += new KeyEventHandler(TxtTextContent_KeyDown);
            }
        }

        private IQueryConditionComponent[] _queryConditionComponentArray;
        public IQueryConditionComponent[] QueryConditionComponentArray
        {
            get { return _queryConditionComponentArray; }
            set
            {
                _queryConditionComponentArray = value;
                foreach (var x in value) 
                {
                    x.GetTxtTextContent().KeyDown += new KeyEventHandler(TxtTextContent_KeyDown);
                }
            }
        }

        void TxtTextContent_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter) 
            {
                this.PageIndex = 0;
                RefreshCurrentPage();
                if (_queryConditionComponent != null)
                {
                    _queryConditionComponent.TxtTextContent.SelectAll();
                }
                if (_queryConditionComponent2 != null)
                {
                    _queryConditionComponent2.TxtTextContent.SelectAll();
                }
            }
        }

        private DataGrid _dataGrid;
        public DataGrid DataGrid
        {
            get
            {
                return _dataGrid;
            }
            set
            {
                if (_dataGrid == value) //防止重复增加菜单项
                {
                    return;
                }
                _dataGrid = value;
                if (_dataGrid is CustomDataGrid)
                {
                    CustomDataGrid dg = _dataGrid as CustomDataGrid;
                    dg.GetItemsFromAllPages = () =>
                    {
                        XElement[] ret = null;
                        List<XElement> xeConditions = new List<XElement>();
                        using (var res = ServerPageUri.HttpPost(PrepareConditionArray(-1)))
                        {
                            ProcessRequest.Process(res, (ResponseMessageInfo resInfo) =>
                            {
                                if (resInfo.ResponseDataMainBody != null)
                                {
                                    //每页要做的事情
                                    ret = resInfo.ResponseDataMainBody.Elements().ToArray();
                                }
                            });
                        }
                        return ret;
                    };

                    //将排序菜单放在这里，是因为只有分页的列表才有服务器端排序的意义
                    var item_order_asc = new MenuItem();
                    item_order_asc.Header = "当前列-顺序";
                    item_order_asc.Click += new RoutedEventHandler(_item_order_asc_Click);

                    var item_order_desc = new MenuItem();
                    item_order_desc.Header = "当前列-倒序";
                    item_order_desc.Click += new RoutedEventHandler(_item_order_desc_Click);


                    dg.ContextMenu.Items.Add(new Separator());
                    dg.ContextMenu.Items.Add(item_order_asc);
                    dg.ContextMenu.Items.Add(item_order_desc);

                    // 总项子项排序
                    if (IsOrderByGeneralItemNameEnabled)
                    {
                        var item_order_general_asc = new MenuItem();
                        item_order_general_asc.Header = "总项-顺序";
                        item_order_general_asc.Click += new RoutedEventHandler(item_order_general_asc_Click);
                        dg.ContextMenu.Items.Add(item_order_general_asc);

                        var item_order_general_desc = new MenuItem();
                        item_order_general_desc.Header = "总项-倒序";
                        item_order_general_desc.Click += new RoutedEventHandler(item_order_general_desc_Click);
                        dg.ContextMenu.Items.Add(item_order_general_desc);

                    }
                    
                    dg.ContextMenu.Items.Add(new Separator());
                }
            }
        }

        /// <summary>
        /// 是否能够按项目总称排序
        /// </summary>
        public static readonly DependencyProperty IsOrderByGeneralItemNameEnabledProperty = DependencyProperty.Register("IsOrderByGeneralItemNameEnabled", typeof(bool), typeof(PageComponent)
            , new PropertyMetadata(false));
        public bool IsOrderByGeneralItemNameEnabled
        {
            get { return (bool)GetValue(IsOrderByGeneralItemNameEnabledProperty); }
            set
            {
                SetValue(IsOrderByGeneralItemNameEnabledProperty, value);
            }
        }

        void item_order_general_desc_Click(object sender, RoutedEventArgs e)
        {
            _sortExpression = "NonSubItemName desc, SampleID, BizItemGroupID, SortOrder, SubitemSN";
            RefreshCurrentPage();
        }

        void item_order_general_asc_Click(object sender, RoutedEventArgs e)
        {
            _sortExpression = "NonSubItemName, SampleID, BizItemGroupID, SortOrder, SubitemSN";
            RefreshCurrentPage();
        }

        private string _sortExpression = "";


        void _item_order_desc_Click(object sender, RoutedEventArgs e)
        {
            if (_dataGrid.CurrentColumn is DataGridTextColumn)
            {
                _sortExpression = ((_dataGrid.CurrentColumn as DataGridTextColumn).Binding as Binding).Path.Path.Split(new string[] { "Element[", "].Value" }, StringSplitOptions.RemoveEmptyEntries)[0];
                _sortExpression += " DESC";
                RefreshCurrentPage();
            }
        }

        void _item_order_asc_Click(object sender, RoutedEventArgs e)
        {
            if (_dataGrid.CurrentColumn is DataGridTextColumn)
            {
                _sortExpression = ((_dataGrid.CurrentColumn as DataGridTextColumn).Binding as Binding).Path.Path.Split(new string[] { "Element[", "].Value" }, StringSplitOptions.RemoveEmptyEntries)[0];
                RefreshCurrentPage();
            }
        }

        private XElement[] PrepareConditionArray(int pageIndex) 
        {
            List<XElement> xeConditionList = new List<XElement>();
            xeConditionList.Add(new XElement("PageSize", this.PageSize));
            xeConditionList.Add(new XElement("PageIndex", pageIndex));
            if (string.IsNullOrEmpty(_sortExpression) == false) 
            {
                xeConditionList.Add(new XElement("SortExpression", _sortExpression));
            }
            //查询条件控件
            if (QueryConditionComponent != null)
            {
                xeConditionList.AddRange(QueryConditionComponent.Conditions);
            }
            if (QueryConditionComponent2 != null)
            {
                xeConditionList.AddRange(QueryConditionComponent2.Conditions);
            }
            if (QueryConditionComponentArray != null)
            {
                foreach (var x in QueryConditionComponentArray)
                {
                    foreach (var y in x.Conditions)
                    {
                        XElement xeExistedCondition = xeConditionList.SingleOrDefault(z => z.Name.LocalName == y.Name.LocalName);
                        if (xeExistedCondition == null) //没有已存在的条件
                        {
                            xeConditionList.Add(y);
                        }
                        else if (y.Name.LocalName == "Sql") //如果是Sql节点的话，就连接条件
                        {
                            xeExistedCondition.SetValue(xeExistedCondition.Value + " " + y.Value);
                        }
                    }
                }
            }
            //其他条件
            if (GetOtherSearchConditions != null)
            {
                xeConditionList.AddRange(GetOtherSearchConditions() ?? new XElement[] { });
            }
            return xeConditionList.ToArray();
        } 

        
        /// <summary>
        /// 翻过此页
        /// </summary>
        /// <param name="actionAtEachPage"></param>
        public void LeafThrough(Action<XElement[]> actionAtEachPage) 
        {
            for (int i = 0; i < PageAmount; i++) 
            {
                List<XElement> xeConditions = new List<XElement>();
                xeConditions.Add(new XElement("PageSize", this.PageSize));
                xeConditions.Add(new XElement("PageIndex", i));

                using (var res = ServerPageUri.HttpPost(PrepareConditionArray(i)))
                {
                    ProcessRequest.Process(res, (ResponseMessageInfo resInfo) =>
                    {
                        if (resInfo.ResponseDataMainBody != null)
                        {
                            //每页要做的事情
                            actionAtEachPage(resInfo.ResponseDataMainBody.Elements().ToArray());
                        }
                    });
                } 
                
            }
        }

        public Func<XElement[]> GetOtherSearchConditions;

        public void InsertItem(int index, XElement xe) 
        {
            if (this.DataGrid.ItemsSource == null)
            {
                this.DataGrid.ItemsSource = new XElement[] { xe };
            }
            else 
            {
                List<XElement> list = (this.DataGrid.ItemsSource as XElement[]).ToList();
                list.Insert(index, xe);
                this.DataGrid.ItemsSource = list.ToArray();
            }
        }

        public void AddItem(XElement xe)
        {
            if (this.DataGrid.ItemsSource == null)
            {
                this.DataGrid.ItemsSource = new XElement[] { xe };
            }
            else
            {
                List<XElement> list = (this.DataGrid.ItemsSource as XElement[]).ToList();
                list.Add(xe);
                this.DataGrid.ItemsSource = list.ToArray();
            }
        }

        public void RemoveItem(XElement xe) 
        {
            List<XElement> list = (this.DataGrid.ItemsSource as XElement[]).ToList();
            list.Remove(xe);
            this.DataGrid.ItemsSource = list.ToArray();
        }

        public Action<XElement[]> PreprocessItemSource;

        private static LoadingWaitingFor loadingWaitingFor = null;
        public void RefreshCurrentPage() 
        {
            if (ShowLoadData)
            {
                if (loadingWaitingFor == null)
                {
                    loadingWaitingFor = new LoadingWaitingFor("正在加载数据，请稍后......");
                }
                loadingWaitingFor.Topmost = true;
                loadingWaitingFor.Show();    //跳出等待窗口
            }
            try
            {
                using (var res = ServerPageUri.HttpPost(PrepareConditionArray(this.PageIndex)))
                {
                    ProcessRequest.Process(res, (ResponseMessageInfo resInfo) =>
                    {
                        if (resInfo.ResponseDataMainBody == null)
                        {
                            this.DataGrid.ItemsSource = null;
                            this.Set(0, 0);
                        }
                        else
                        {
                            XElement[] xeArray = resInfo.ResponseDataMainBody.Elements().ToArray();
                            if (PreprocessItemSource != null)
                            {
                                PreprocessItemSource(xeArray);
                            }

                            if (this.DataGrid is CustomDataGrid)
                            {
                                CustomDataGrid dg = _dataGrid as CustomDataGrid;
                                if (dg.AsTreeView)
                                {
                                    dg.BindAsTreeView(xeArray);
                                }
                                else 
                                {
                                    dg.ItemsSource = xeArray;
                                }
                                this.Set(resInfo.ItemAmount, resInfo.PageAmount);
                                dg.ExportTotalNum = resInfo.ItemAmount;
                            }
                            else
                            {
                                this.DataGrid.ItemsSource = xeArray;
                                this.Set(resInfo.ItemAmount, resInfo.PageAmount);
                            }
                           
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                Tools.ShowErrorInfo("查询失败", ex.Message);
            }
            finally
            {
                if (ShowLoadData)
                {
                    loadingWaitingFor.Hide();
                }
            }
        }

        public static readonly DependencyProperty PageSizeProperty = DependencyProperty.Register("PageSize", typeof(int), typeof(PageComponent)
            , new PropertyMetadata(20, new PropertyChangedCallback(OnPageSizeProperyChanged)));
        public int PageSize
        {
            get { return (int)GetValue(PageSizeProperty); }
            set
            {
                SetValue(PageSizeProperty, value);
            }
        }
        private static void OnPageSizeProperyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        { }

        /// <summary>
        /// 是否显示加载数据......
        /// </summary>
        public bool ShowLoadData = true;

        public int PageIndex { get; set; }


        public int PageAmount { get; set; }

        public void Set(int itemAmount, int pageAmount) 
        {
            PageAmount = pageAmount;
            if (PageIndex > 0 && PageIndex > PageAmount - 1)//由于检索条件的变化导致当前页大于总页数
            {
                PageIndex = PageAmount;
            }
 

            int recordBegin = PageIndex * PageSize + 1;
            this.txtCurrentRecordBegin.Text = recordBegin.ToString();
            this.txtCurrentRecordEnd.Text = (itemAmount >= (recordBegin + PageSize) ? (recordBegin + PageSize - 1) : itemAmount).ToString();
            this.txtItemAmount.Text = itemAmount.ToString();

            this.txtCurrentPage.Text = (PageIndex + 1).ToString();
            this.txtPageAmount.Text = (PageAmount).ToString();

            
            if (PageAmount == 0 || PageAmount == 1) 
            {
                this.imgHome.IsEnabled = false;
                this.imgHome.Opacity = 0.5;
                this.imgPrevious.IsEnabled = false;
                this.imgPrevious.Opacity = 0.5;
                this.imgNext.IsEnabled = false;
                this.imgNext.Opacity = 0.5;
                this.End.IsEnabled = false;
                this.End.Opacity = 0.5;
                this.txtgopage.Opacity = 0.5;
                this.txtgopage.IsReadOnly = true;
            }
            else if (this.PageIndex == 0) 
            {
                this.imgHome.IsEnabled = false;
                this.imgHome.Opacity = 0.5;
                this.imgPrevious.IsEnabled = false;
                this.imgPrevious.Opacity = 0.5;
                this.imgNext.IsEnabled = true;
                this.imgNext.Opacity = 1;
                this.End.IsEnabled = true;
                this.End.Opacity = 1;
                this.txtgopage.Opacity = 1;
                this.txtgopage.IsReadOnly = false;
            }
            else if (this.PageIndex == (PageAmount - 1))
            {
                this.imgHome.IsEnabled = true;
                this.imgHome.Opacity = 1;
                this.imgPrevious.IsEnabled = true;
                this.imgPrevious.Opacity = 1;
                this.imgNext.IsEnabled = false;
                this.imgNext.Opacity = 0.5;
                this.End.IsEnabled = false;
                this.End.Opacity = 0.5;
                this.txtgopage.Opacity = 1;
                this.txtgopage.IsReadOnly = false;
            }
            else 
            {
                this.imgHome.IsEnabled = true;
                this.imgHome.Opacity = 1;
                this.imgPrevious.IsEnabled = true;
                this.imgPrevious.Opacity = 1;
                this.imgNext.IsEnabled = true;
                this.imgNext.Opacity = 1;
                this.End.IsEnabled = true;
                this.End.Opacity = 1;
                this.txtgopage.Opacity = 1;
                this.txtgopage.IsReadOnly = false;
            }
        }

        public void GoProvious() 
        {
            if (PageIndex >= 1)
            {
                PageIndex--;
                RefreshCurrentPage();
            }
        }

        public void GoNext() 
        {
            if (PageIndex < PageAmount - 1)
            {
                PageIndex++;
                RefreshCurrentPage();
            }
        }

        //上一页
        private void imgPrevious_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            PageIndex--;
            RefreshCurrentPage();
        }

        //下一页
        private void imgNext_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            PageIndex++;
            RefreshCurrentPage();
        }

        //首页
        private void imgHome_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            PageIndex = 0;
            RefreshCurrentPage();
        }

        //尾页
        private void End_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            PageIndex = PageAmount - 1;
            RefreshCurrentPage(); 
        }

        //跳转
        private void Gopage_Click(object sender, RoutedEventArgs e)
        {
            int pageIndex;//客户输入的页数，不是从0开始的
            if (!int.TryParse(this.txtgopage.Text, out pageIndex))
            {
                MessageBox.Show("请输入正确的页数");
            }
            else if (pageIndex < 1)
            {
                MessageBox.Show("请输入大于0的页数");
            }
            else if (pageIndex > PageAmount)
            {
                MessageBox.Show("请不要输入大于总页数内的页数");
            }
            else
            {
                this.PageIndex = pageIndex - 1;
                RefreshCurrentPage();
            }
        }

        //回车跳转
        private void txtgopage_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter) 
            {
                Gopage_Click(null, null);
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }

    }
}
